import { useState, useEffect, useCallback } from 'react'
import { getAppInfo } from '@/utils/bridge'
import { APPCONFIG } from '@/config/constant'

const RTL_LIST = new Set(['ar'])
const SUPPORT_LANG = ['en', 'ar', 'zh', 'id', 'ja']

const getBrowserInfo = () => {
  const info = {}

  info.lang = window.navigator.language.slice(0, 2).toLowerCase()

  return info
}

function useLang({ langPath, isConfigDir = true, languageControl = SUPPORT_LANG }) {
  let [lang, setLang] = useState('')
  let [content, setContent] = useState()
  let [dir, setDir] = useState('ltr')
  let [appInfo, setAppInfo] = useState({})

  // 获取语言类型
  const getLangType = useCallback(async (isConfigDir) => {
    // TODO: get lang
    let appInfo = window.lz.isApp ? await getAppInfo() : getBrowserInfo()
    setAppInfo(appInfo)
    let { lang } = appInfo

    // NOTE: 避免缺失语言文件导致页面崩溃
    if (!languageControl.includes(lang)) {
      lang = languageControl[0]
    }

    setLang(lang)

    // TODO: get dir
    const direction = RTL_LIST.has(lang.toLowerCase()) ? 'rtl' : 'ltr'
    setDir(direction)
    window.langDir = direction

    const { documentElement } = window.document
    documentElement.setAttribute('lang', lang)
    isConfigDir && documentElement.setAttribute('dir', direction)
  }, [])

  // 载入翻译文件
  useEffect(() => {
    if (langPath && lang) {
      import('@/' + langPath + '/lang/' + lang + '.json')
        .then(({ title, content }) => {
          window.langContent = content
          setContent(content)
          document.title = title || APPCONFIG.NAME
        })
        .catch((error) => console.error(error))
    }
  }, [langPath, lang])

  // 载入样式文件
  useEffect(() => {
    if (dir === 'rtl' && langPath) {
      import('@/' + langPath + '/style/' + dir + '.scss').catch((error) => console.error(error))
    }
  }, [langPath, dir])

  useEffect(() => {
    if (langPath) {
      getLangType({ isConfigDir })
    }
  }, [langPath, isConfigDir])

  return { lang, content, dir, appInfo }
}

export default useLang
